package com.xtgg.baby;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.RequestParams;
import com.xtgg.R;
import com.xtgg.baby.DeviceListActivity.BleReceiver;
import com.xtgg.login.LoginActivity;
import com.xtgg.manager.BaseActivity;
import com.xtgg.model.Resp;
import com.xtgg.more.AddNewBabyActivity;
import com.xtgg.sys.Constants;
import com.xtgg.sys.DemoApp;
import com.xtgg.util.ImageLoaderHelper;
import com.xtgg.util.MgqDataHandler;
import com.xtgg.util.MgqRestClient;
import com.xtgg.util.PreferencesUtils;
import com.xtgg.util.ToastUtil;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class BabyListActivity extends BaseActivity implements OnClickListener {
	MyAdapter mAdapter;
	JSONArray mArray = null;

	BleReceiver mReceiver;
	public class BleReceiver extends BroadcastReceiver
	{
		@SuppressLint("NewApi")
		public void onReceive(Context paramContext, Intent paramIntent)
	    {
			if (paramIntent.getAction().equals("com.fb.ble.action.device_connect"))
			{
				if(mAdapter != null) mAdapter.notifyDataSetChanged();
			}
	    }
	}
	
	protected void onDestroy()
	{
		super.onDestroy();
		unregisterReceiver(mReceiver);
	}

	protected void onResume()
	{
		super.onResume();
		reloadData();
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_baby_list);
		
		mReceiver = new BleReceiver();
		IntentFilter localIntentFilter = new IntentFilter();
	    localIntentFilter.addAction("com.fb.ble.action.device_connect");
	    registerReceiver(mReceiver, localIntentFilter);

		((TextView) findViewById(R.id.center)).setText("宝宝");
		((Button) findViewById(R.id.right))
				.setCompoundDrawablesWithIntrinsicBounds(0, 0,
						R.drawable.ic_add_device, 0);
		findViewById(R.id.right).setOnClickListener(this);
		findViewById(R.id.left).setVisibility(View.INVISIBLE);

		final PullToRefreshListView ptrlvHeadlineNews = (PullToRefreshListView) findViewById(R.id.listview);
		ptrlvHeadlineNews
				.setMode(com.handmark.pulltorefresh.library.PullToRefreshBase.Mode.DISABLED);
		ptrlvHeadlineNews
				.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						sendHttpRequest();
					}
				});

		ListView listview = ptrlvHeadlineNews.getRefreshableView();
		mAdapter = new MyAdapter();
		listview.setAdapter(mAdapter);
		listview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
			}
		});

		sendHttpRequest();
	}

	class MyAdapter extends BaseAdapter implements OnClickListener {
		public int getCount() {
			return mArray != null ? mArray.size() : 0;
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		@SuppressLint("NewApi")
		public View getView(int position, View convertView, ViewGroup parent) {
			FoodHolder foodHold = null;

			if (convertView == null) {
				LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				foodHold = new FoodHolder();

				convertView = mInflater.inflate(R.layout.item_baby, null);
				foodHold.img = (ImageView) convertView.findViewById(R.id.img);
				foodHold.name = (TextView) convertView.findViewById(R.id.name);
				foodHold.sex = (TextView) convertView.findViewById(R.id.sex);

				foodHold.device0 = (RelativeLayout) convertView
						.findViewById(R.id.device0);
				foodHold.device1 = (RelativeLayout) convertView
						.findViewById(R.id.device1);
				foodHold.device2 = (RelativeLayout) convertView
						.findViewById(R.id.device2);
				foodHold.device3 = (RelativeLayout) convertView
						.findViewById(R.id.device3);
				foodHold.user = (RelativeLayout) convertView
						.findViewById(R.id.user);

				foodHold.status0 = (ImageView) convertView
						.findViewById(R.id.status0);
				foodHold.status1 = (ImageView) convertView
						.findViewById(R.id.status1);
				foodHold.status2 = (ImageView) convertView
						.findViewById(R.id.status2);
				foodHold.status3 = (ImageView) convertView
						.findViewById(R.id.status3);
				
				foodHold.tip0 = (TextView) convertView.findViewById(R.id.tip0);
				foodHold.tip1 = (TextView) convertView.findViewById(R.id.tip1);
				foodHold.tip2 = (TextView) convertView.findViewById(R.id.tip2);
				foodHold.tip3 = (TextView) convertView.findViewById(R.id.tip3);

				foodHold.device_name0 = (TextView) convertView
						.findViewById(R.id.device_name0);
				foodHold.device_name1 = (TextView) convertView
						.findViewById(R.id.device_name1);
				foodHold.device_name2 = (TextView) convertView
						.findViewById(R.id.device_name2);
				foodHold.device_name3 = (TextView) convertView
						.findViewById(R.id.device_name3);

				foodHold.bare0 = (TextView) convertView
						.findViewById(R.id.bare0);
				foodHold.bare1 = (TextView) convertView
						.findViewById(R.id.bare1);
				foodHold.bare2 = (TextView) convertView
						.findViewById(R.id.bare2);
				foodHold.bare3 = (TextView) convertView
						.findViewById(R.id.bare3);

				foodHold.line0 = (View) convertView.findViewById(R.id.line0);
				foodHold.line1 = (View) convertView.findViewById(R.id.line1);
				foodHold.line2 = (View) convertView.findViewById(R.id.line2);
				foodHold.line3 = (View) convertView.findViewById(R.id.line3);

				convertView.setTag(foodHold);
			} else {
				foodHold = (FoodHolder) convertView.getTag();
			}

			foodHold.device0.setVisibility(View.GONE);
			foodHold.device1.setVisibility(View.GONE);
			foodHold.device2.setVisibility(View.GONE);
			foodHold.device3.setVisibility(View.GONE);

			foodHold.line0.setVisibility(View.GONE);
			foodHold.line1.setVisibility(View.GONE);
			foodHold.line2.setVisibility(View.GONE);
			foodHold.line3.setVisibility(View.GONE);

			JSONObject item = mArray.getJSONObject(position);
			JSONArray array = item.getJSONArray("devices");
			int count = array.size();
			for(int i = 0; i < count && i < 4; i++)
			{
				JSONObject obj = array.getJSONObject(i);
				if(i == 0)
				{
					foodHold.device0.setVisibility(View.VISIBLE);
					foodHold.line0.setVisibility(View.VISIBLE);
					foodHold.device_name0.setText(obj.getString("d_nickname"));
					foodHold.bare0.setText("设备剩余电量" + obj.getString("power"));
					foodHold.device0.setTag(String.valueOf(position));
					foodHold.device0.setOnClickListener(this);
					
					if(obj.getIntValue("status") == 3) foodHold.status0.setImageResource(R.drawable.ic_device_off);
					else foodHold.status0.setImageResource(R.drawable.ic_device_on);
				}
				else if(i == 1)
				{
					foodHold.device1.setVisibility(View.VISIBLE);
					foodHold.line1.setVisibility(View.VISIBLE);
					foodHold.device_name1.setText(obj.getString("d_nickname"));
					foodHold.bare1.setText("设备剩余电量" + obj.getString("power"));
					foodHold.device1.setTag(String.valueOf(position));
					foodHold.device1.setOnClickListener(this);
					
					if(obj.getIntValue("status") == 3) foodHold.status1.setImageResource(R.drawable.ic_device_off);
					else foodHold.status1.setImageResource(R.drawable.ic_device_on);
				}
				else if(i == 2)
				{
					foodHold.device2.setVisibility(View.VISIBLE);
					foodHold.line2.setVisibility(View.VISIBLE);
					foodHold.device_name2.setText(obj.getString("d_nickname"));
					foodHold.bare2.setText("设备剩余电量" + obj.getString("power"));
					foodHold.device2.setTag(String.valueOf(position));
					foodHold.device2.setOnClickListener(this);
					
					if(obj.getIntValue("status") == 3) foodHold.status2.setImageResource(R.drawable.ic_device_off);
					else foodHold.status2.setImageResource(R.drawable.ic_device_on);
				}
				else if(i == 3)
				{
					foodHold.device3.setVisibility(View.VISIBLE);
					foodHold.line3.setVisibility(View.VISIBLE);
					foodHold.device_name3.setText(obj.getString("d_nickname"));
					foodHold.bare3.setText("设备剩余电量" + obj.getString("power"));
					foodHold.device3.setTag(String.valueOf(position));
					foodHold.device3.setOnClickListener(this);
					
					if(obj.getIntValue("status") == 3) foodHold.status3.setImageResource(R.drawable.ic_device_off);
					else foodHold.status3.setImageResource(R.drawable.ic_device_on);
				}
				
				boolean result = false;
				List<BluetoothGatt> list = ((DemoApp)getApplicationContext()).deviceInfo;
				int size = list.size();
				for(int j = 0; j < size; j++)
				{
					if(list.get(j).getDevice().getAddress().equals(obj.getString("andriod_code")))
					{
						result = true;
						
						if(i == 0)
						{
							foodHold.tip0.setVisibility(View.INVISIBLE);
						}
						else if(i == 1)
						{
							foodHold.tip1.setVisibility(View.INVISIBLE);
						}
						else if(i == 2)
						{
							foodHold.tip2.setVisibility(View.INVISIBLE);
						}
						else if(i == 3)
						{
							foodHold.tip3.setVisibility(View.INVISIBLE);
						}
					}
				}
				
				if(!result)
				{
					if(i == 0)
					{
						foodHold.tip0.setVisibility(View.VISIBLE);
					}
					else if(i == 1)
					{
						foodHold.tip1.setVisibility(View.VISIBLE);
					}
					else if(i == 2)
					{
						foodHold.tip2.setVisibility(View.VISIBLE);
					}
					else if(i == 3)
					{
						foodHold.tip3.setVisibility(View.VISIBLE);
					}
				}
			}

			foodHold.name.setText(item.getString("childname"));
			if(item.getIntValue("sex") == 0) foodHold.sex.setText("男宝宝/女宝宝");	
			else foodHold.sex.setText(item.getIntValue("sex") == 1 ? "男宝宝" : "女宝宝");
			ImageLoaderHelper.displayImage(R.drawable.img_default,
					foodHold.img, item.getString("headurl"), 5);
			
			foodHold.user.setTag(String.valueOf(position));
			foodHold.user.setOnClickListener(this);
			
			foodHold.status0.setTag(String.valueOf(position));
			foodHold.status0.setOnClickListener(this);
			foodHold.status1.setTag(String.valueOf(position));
			foodHold.status1.setOnClickListener(this);
			foodHold.status2.setTag(String.valueOf(position));
			foodHold.status2.setOnClickListener(this);
			foodHold.status3.setTag(String.valueOf(position));
			foodHold.status3.setOnClickListener(this);
			
			return convertView;
		}

		@Override
		public void onClick(View arg0) {
			int position = Integer.valueOf((String) arg0.getTag());
			if (arg0.getId() == R.id.user) {
				Intent intent = new Intent(BabyListActivity.this,
						ModifyBabyActivity.class);
				intent.putExtra("info", mArray.getJSONObject(position)
						.toJSONString());
				startActivity(intent);
			}
			else if(arg0.getId() == R.id.status0)
			{
				sendHttpRequest(Integer.valueOf((String)arg0.getTag()),0);
			}
			else if(arg0.getId() == R.id.status1)
			{
				sendHttpRequest(Integer.valueOf((String)arg0.getTag()),1);
			}
			else if(arg0.getId() == R.id.status2)
			{
				sendHttpRequest(Integer.valueOf((String)arg0.getTag()),2);
			}
			else if(arg0.getId() == R.id.status3)
			{
				sendHttpRequest(Integer.valueOf((String)arg0.getTag()),3);
			}
			else
			{
				JSONArray array = mArray.getJSONObject(position).getJSONArray("devices");
				
				Intent intent = new Intent(BabyListActivity.this,
						DeviceInfoActivity.class);
				intent.putExtra("info", array.getJSONObject(arg0.getId() - R.id.device0)
						.toJSONString());
				intent.putExtra("baby", mArray.getJSONObject(position).toJSONString());
				startActivity(intent);
			}
		}
	}
	
	private void sendHttpRequest(int baby,int device) {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("state").equals("1")) {
					reloadData();
				}
				else if (ruser.getString("state").equals("2"))
				{
					showExitDialog();
				} else {
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}
			}
		};
		
		JSONObject item = mArray.getJSONObject(baby).getJSONArray("devices").getJSONObject(device);

		RequestParams params = new RequestParams();
		params.put("act", "operateDevice");
		params.put("userid", PreferencesUtils.getString(this, "userid"));
		params.put("deviceid", item.getString("deviceid"));
		params.put("childid", mArray.getJSONObject(baby).getString("childid"));
		if(item.getIntValue("status") == 3) params.put("type", 1);
		else params.put("type", 3);
		MgqRestClient.post(Constants.DEVICEMGT, params, loginHandler);
	}

	public final class FoodHolder {
		public ImageView img;
		public TextView name;
		public TextView sex;

		RelativeLayout device0;
		RelativeLayout device1;
		RelativeLayout device2;
		RelativeLayout device3;
		RelativeLayout user;

		public ImageView status0;
		public ImageView status1;
		public ImageView status2;
		public ImageView status3;

		public TextView tip0;
		public TextView tip1;
		public TextView tip2;
		public TextView tip3;

		public TextView device_name0;
		public TextView device_name1;
		public TextView device_name2;
		public TextView device_name3;

		public TextView bare0;
		public TextView bare1;
		public TextView bare2;
		public TextView bare3;

		public View line0;
		public View line1;
		public View line2;
		public View line3;
	}

	public void reloadData() {
		if(mArray != null)
		{
			mArray.removeAll(mArray);
			mAdapter.notifyDataSetChanged();
		}
		
		sendHttpRequest();
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.left:
			finish();
			break;

		case R.id.right:
			showSec();
			break;
		}
	}

	void showSec()
	{
		new AlertDialog.Builder(this).setTitle("列表框").setItems(
				new String[] { "新增宝宝","新增设备","返回" }, new DialogInterface.OnClickListener()
				{
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						if(arg1 == 0)
						{
							startActivity(new Intent(BabyListActivity.this, AddNewBabyActivity.class));
						}
						else if(arg1 == 1)
						{
							BluetoothAdapter.getDefaultAdapter().enable();
							startActivity(new Intent(BabyListActivity.this,DeviceSearchActivity.class));
						}
					}
				}).show();
	}
	
	private void sendHttpRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				Resp ruser = JSON.parseObject(response, Resp.class);

				if (ruser.getState().equals("1")) {
					mArray = JSON.parseObject(response).getJSONArray("data");
					mAdapter.notifyDataSetChanged();

					findViewById(R.id.tip).setVisibility(View.INVISIBLE);
				} 
				else if (ruser.getState().equals("2"))
				{
					showExitDialog();
				} 
				else 
				{
					findViewById(R.id.tip).setVisibility(View.VISIBLE);
				}
			}
		};
		// -----------------------

		RequestParams params = new RequestParams();
		params.put("act", "getMyChildList");
		params.put("userid", PreferencesUtils.getString(this, "userid"));

		MgqRestClient.get(Constants.DEVICEMGT, params, loginHandler);
	}
	
	 private long mExitTime;
	    public boolean onKeyDown(int keyCode, KeyEvent event) 
	    {
	    	if (keyCode == KeyEvent.KEYCODE_BACK) {
	    		if ((System.currentTimeMillis() - mExitTime) > 2000) 
	    		{
	    			Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
	    			mExitTime = System.currentTimeMillis();	
	    		} else {
	    			finish();
	    		}
	    		return true;
	    	}
	    	return super.onKeyDown(keyCode, event);
	    }
}
